import React from 'react';
import { Button, message, Icon, Row, Col } from 'antd';
import './singleFile.less';

class SingleFile extends React.Component {
  static getDerivedStateFromProps(nextProps) {
    // Should be a controlled component.
    if ('value' in nextProps) {
      return {
        ...(nextProps.value || {})
      };
    }
    return null;
  }
  constructor() {
    super();
    this.state = {
      file: ''
    };

    this.fileInputEl = React.createRef();
  }

  componentDidMount() {}

  onFileChange = e => {
    if (e.currentTarget.files[0].type !== 'text/plain') {
      message.warning('请选择.txt的文件');
      return;
    }
    this.inputHandleChange(e.currentTarget.files[0]);
  };

  inputHandleChange(value) {
    this.triggerChange(value);
  };
  triggerChange = changedValue => {
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(Object.assign({}, { file: changedValue }, changedValue));
      if (this.props.isClearFile) {
        this.fileInputEl.current.value = '';
      }
    }
  };

  remove = () => {
    this.triggerChange('');
    this.fileInputEl.current.value = '';
  };

  render() {
    return (
      <div className='file-upload'>
        <Row type='flex' gutter={10}>
          <Col>
            <Button onClick={() => this.fileInputEl.current.click()}>选择文件</Button>
          </Col>
          <Col>
            {this.state.file && (
              <div>
                {this.state.file.name}
                {this.state.file.name && (
                  <Icon
                    type='close-circle'
                    style={{ cursor: 'pointer', color: '#006eff', marginLeft: '10px' }}
                    onClick={this.remove}
                  />
                )}
              </div>
            )}
          </Col>
        </Row>
        <input ref={this.fileInputEl} name='file' hidden type='file' onInput={this.onFileChange} />
      </div>
    );
  }
}

export default SingleFile;
